package com.comptel.actions.discovery;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NameClassPair;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;

import com.comptel.actions.ActionProvider;

public class DiscoveryMethodJ2EE implements DiscoveryMethod {

	
		
	@Override
	public Map<String, ActionProvider> discover() {

		String prefix = "ejb/actions";
		NamingEnumeration<NameClassPair> entries;
		Map<String, ActionProvider> providers;
		try {
			InitialContext ctx = getContext();	
			 entries = ctx.list(prefix);
			 prefix += "/";
			 providers = collectProviders(prefix, entries, ctx);
			 
		} catch (NamingException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		return providers;
	}

	private InitialContext getContext() throws NamingException {
        Properties props = new Properties();
        props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.enterprise.naming.SerialInitContextFactory");
        props.setProperty("org.omg.CORBA.ORBInitialHost", "localhost");
        props.setProperty("org.omg.CORBA.ORBInitialPort", "3700");

        return new InitialContext(props);
	}
        
	private Map<String, ActionProvider> collectProviders(String prefix, NamingEnumeration<NameClassPair> entries, InitialContext ctx) throws NamingException {
		Object entry;
		
		Map<String, ActionProvider> providers = new HashMap<String, ActionProvider>();
		ActionProvider ap;
		String key;
		 
		while (entries.hasMore()) {
			NameClassPair pair = entries.next();
			System.out.println(pair);
			entry = ctx.lookup(prefix+pair.getName());
			System.out.println(entry);
			if (entry instanceof ActionProvider) {
				ap = (ActionProvider)entry;
				key = ap.getProviderName();
				System.out.println("PROVIDER --> "+ap.getProviderName());
				if (providers.get(key) == null) {
					providers.put(key, ap);
					System.out.println("*** ADDED ***");
				}
			}
		 }
		 return providers;
	}

}
